# -*- coding: utf-8 -*-
"""
django使用的报错中间件
"""
import os
import json
import traceback
import sys
import urllib
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from threading import Thread


class ErrorMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception):

        t = Thread(
            target=send_error,
            args=(sys.exc_info()[0].__name__, traceback.format_exc(), request),
        )
        t.start()


def send_error(error_type, code, request):
    url = settings.MAGIC_CUBE["url"] + "/api/errors/error/"
    token = settings.MAGIC_CUBE["token"]
    version = settings.MAGIC_CUBE.get("version")
    meta = request.META
    if not version:
        try:
            version = os.popen("git rev-parse HEAD").read()
        except:
            version = ""

    if "HTTP_X_FORWARDED_FOR" in request.META:
        ip = request.META["HTTP_X_FORWARDED_FOR"]
    else:
        ip = request.META["REMOTE_ADDR"]

    params = {
        "token": token,
        "code": code,
        "errorType": error_type,
        # 'json_data': json_data,
        "clientUser": ip,
        "version": version,
    }

    data = {}

    data["ip"] = ip
    data["user_agent"] = meta.get("HTTP_USER_AGENT")
    data["path"] = request.path
    data["query_string"] = meta.get("QUERY_STRING")
    try:
        data["body"] = request.body.decode("utf-8")
    except:
        data["body"] = ""
    data["method"] = request.method
    params["jsonData"] = json.dumps(data)

    data = json.dumps(params)
    data = bytes(data, "utf-8")
    request = urllib.request.Request(url, data=data)
    response = urllib.request.urlopen(request)
    # html = response.read().decode('utf-8')
